﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace UM_SERVER.Net
{
    class SystemTcpPortListener : TcpPortListener
    {
        public SystemTcpPortListener(int Port, MessageListener messageListener)
            : base(Port, messageListener)
        {
            
        }

        public override void Init()
        {
            //创建监听器
            this.PortProcessor = new TcpListener(this.Port); 
            PortProcessor.Start();
            //创建监听线程
            this.CurrentThread = new Thread(new ThreadStart(this.Listen));
            CurrentThread.Name = "Listener of TCP Port of : " + this.Port;
            CurrentThread.Start();
        }

        protected override void Listen()
        {
            //循环监听
            while(IS_LOOP_LISTEN)
            {
                //得到用户连接
                Socket UserSocket = this.PortProcessor.AcceptSocket();
                this.Listener.UserSocket = UserSocket;
                this.Listener.Init();
                //触发事件
                OnOnUserConnected(new OnUserConnectedEventArgs(UserSocket));
            }
        }

        public override void Dispose()
        {
            IS_LOOP_LISTEN = false;
            this.Listener.Dispose();

            try
            {
                if (this.PortProcessor != null)
                {
                    this.PortProcessor.Stop();
                }
            }
            catch
            {}

            if(this.CurrentThread != null)
            {
                this.CurrentThread.Abort();
            }
        }
    }
}
